import { parse } from 'qs'
import { message } from 'antd'
import { isEmpty, cloneDeep, pick } from 'lodash'
import {
	getDetail,
	addUser,
	editUser,
	getRoleTree,
	getOrganize,
	resetPwd,
	getDuty
} from './userInfoServ'
import { hashHistory } from 'dva/router'
// import Verify from '../common/verify';
// import AppBus from '../../../../utils/bus'
import config from '../../../../config/config'

//树形结构转列表
function tree2list(tree) {
	const dataList = [];
	const generateList = (data) => {
		for (let i = 0; i < data.length; i++) {
			const node = data[i];
			dataList.push(node);
			if (node.children && node.children.length > 0) {
				generateList(node.children);
			}
		}
	};
	generateList(tree);
	return dataList.slice(0);
}

const detail = {
	id: '',
	password: '',
	confirmPassword: '',
	phone: '',
	userName: '',
	realName: '',
	orgId: '',
	appId: '',
	appRoleList: [{
		appIds: '',
		roleIds: '',
	}],
	//职能id
	dutyId: '',

	//展示需要
	roleList: [],
}

const defaultState = {
	detail: cloneDeep(detail),
	//类型：add或edit
	type: '',
	//可搜索树
	expandedKeys: [],
	searchValue: '',
	autoExpandParent: false,
	//tree被选中的节点
	checkedKeys: [],

	roleTree: [],
	organizeList: [],
	//sys-系统管理，org-组织管理
	roleType: '',
	//职能列表
	dutyList: []
};

const userInfoModel = {
	state: cloneDeep(defaultState),
	subscriptions: {
		setup({ dispatch, history }) {
			history.listen(location => {
				if (userInfoModel.pathname == location.pathname) {
					dispatch({ type: 'valueNull' });
					let title = '';
					switch (location.query.type) {
						case 'edit':
							title = '用户编辑';
							break;
						case 'add':
							title = '用户新增';
							break;
					}
					dispatch({ type: 'app/setTabTitle', payload: { title: title, location } });
					dispatch({ type: 'init', payload: location.query });
				}
			})
		},
	},
	effects: {

		*init({ payload }, { put, call, select }) {
			let state = yield select(e => e[namespace]);
			yield put({ type: 'getRoleTree' });
			yield put({ type: 'getOrganize' });
			if (config.appId == 3) {
				yield put({ type: 'getDuty' });
			}
			if (payload.type == 'add') {
				yield put({ type: 'store', payload: { type: payload.type, roleType: 'sys' } });
			} else {
				state.detail.id = payload.id;
				yield put({ type: 'store', payload: { type: payload.type, detail: state.detail } });
				yield put({ type: 'getDetail' });
			}
		},

		*valueNull({ payload }, { put, call, select }) {
			yield put({ type: 'store', payload: cloneDeep(defaultState) });
		},

		*updateModel({ payload: obj }, { put, call, select }) {
			yield put({ type: 'store', payload: { ...obj } });
		},

		*getDetail({ payload }, { put, call, select }) {
			let state = yield select(e => e[namespace]);
			try {
				let { data, resultCode } = yield call(getDetail, { id: state.detail.id });
				if (resultCode == 0) {
					if (!data) { return }
					let roleType = 'sys';
					if (config.appId == 4) {
						if (data.appId == 3) {
							roleType = 'org';
						}
					}
					data.password = data.password.substr(0, 10);
					data.confirmPassword = data.password;
					let checkedKeys = [];
					data.roleList.forEach((e, i) => { checkedKeys.push(String(e.id)) })
					yield put({ type: 'store', payload: { detail: data, roleType: roleType, checkedKeys: checkedKeys } });
				}
			} catch (error) {
				console.error(error);
			}
		},

		*getDuty({ payload }, { put, call, select }) {
			let state = yield select(e => e[namespace]);
			try {
				let { data, resultCode } = yield call(getDuty);
				if (resultCode == 0) {
					if (!data) { return }
					yield put({ type: 'store', payload: { dutyList: data } });
				}
			} catch (error) {
				console.error(error);
			}
		},

		*getRoleTree({ payload }, { put, call, select }) {
			let state = yield select(e => e[namespace]);
			try {
				let { data, resultCode } = yield call(getRoleTree);
				if (resultCode == 0) {
					if (!data) { return }
					yield put({ type: 'store', payload: { roleTree: data } });
				}
			} catch (error) {
				console.error(error);
			}
		},

		*getOrganize({ payload }, { put, call, select }) {
			let state = yield select(e => e[namespace]);
			try {
				let { data, resultCode } = yield call(getOrganize);
				if (resultCode == 0) {
					if (!data) { return }
					data.forEach((e) => { e.id = String(e.id) })
					yield put({ type: 'store', payload: { organizeList: data } });
				}
			} catch (error) {
				console.error(error);
			}
		},

		*save({ payload }, { put, call, select }) {
			let state = yield select(e => e[namespace]), detail = state.detail;
			try {
				if (state.type == 'add') {
					let params = {
						userName: detail.userName.trim(),
						realName: detail.realName.trim(),
						password: detail.password,
						confirmPassword: detail.confirmPassword,
						phone: detail.phone,
						dutyId:detail.dutyId,
						appIds: String(config.appId),
					}
					if (state.roleType == 'sys') {
						let appIds = [], roleIds = [];
						detail.roleList.forEach((e, i) => {
							if (e.applicationId && appIds.indexOf(e.applicationId) == -1) {
								appIds.push(e.applicationId)
							}
							roleIds.push(e.id);
						})
						params.appIds = appIds.join(',');
						params.roleIds = roleIds.join(',');
					}
					if (state.roleType == 'org') {
						params.appIds = '3';
						params.orgId = detail.orgId;
					}
					let { data, resultCode } = yield call(addUser, params);
					if (resultCode == 0) {
						message.success('新增成功');
						hashHistory.push(MODULE_TO_ROUTES[namespace].urlArray[0])
					}
				} else {
					let params = {
						id: detail.id,
						userName: detail.userName,
						realName: detail.realName,
						phone: detail.phone,
						dutyId:detail.dutyId,
						appIds: String(config.appId),
					}
					if (state.roleType == 'sys') {
						let appIds = [], roleIds = [];
						detail.roleList.forEach((e, i) => {
							if (e.applicationId && appIds.indexOf(e.applicationId) == -1) {
								appIds.push(e.applicationId)
							}
							roleIds.push(e.id);
						})
						params.appIds = appIds.join(',');
						params.roleIds = roleIds.join(',')

					}
					if (state.roleType == 'org') {
						params.appIds = '3';
						params.orgId = detail.orgId;
					}
					let { data, resultCode } = yield call(editUser, params);
					if (resultCode == 0) {
						message.success('保存成功');
						hashHistory.push(MODULE_TO_ROUTES[namespace].urlArray[0])
					}
				}
			} catch (error) {
				console.error(error);
			}
		},

		*resetPwd({ payload }, { put, call, select }) {
			let state = yield select(e => e[namespace]);
			try {
				let { data, resultCode } = yield call(resetPwd, { userId: state.detail.id });
				if (resultCode == 0) {
					message.success('重置密码成功，密码为00000000')
				}
			} catch (error) {
				console.error(error);
			}
		},

	},
	reducers: {
		store(preState, action) {
			return Object.assign({}, preState, action.payload);
		},
	}
}
export default userInfoModel
